<%--
  Created by IntelliJ IDEA.
  User: 薛之谦
  Date: 2025/8/21
  Time: 23:03
  To change this template use File | Settings | File Templates.
--%>
<%@ page import="com.xtedu.examproject.entity.User" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    User user = request.getSession().getAttribute("user") == null ? new User() : (User) session.getAttribute("user");
    int roleId = user.getRoleId();
%>
<c:set var="roleId" value="<%= roleId %>"/>
<jsp:include page="header.jsp"/>
<style>
    .content-area {
        background-color: #ffffff;
        min-height: calc(100vh - 56px);
    }

    .role-select {
        width: auto;
        display: inline-block;
    }

    .edit-role-btn, .save-role-btn, .cancel-role-btn {
        margin-left: 5px;
    }

    .filter-section {
        background-color: #f8f9fa;
        border-radius: 8px;
    }
</style>
<div class="content-area p-4">
    <!-- 页面标题和其他操作按钮 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="bi bi-journal-text"></i>
            <span>用户管理</span>
        </h2>
    </div>
    <!-- 筛选区域 -->
    <div class="filter-section p-3 mb-4">
        <div class="row g-3">
            <div class="col-md-2" style="text-align: center;">
                <jsp:include page="adduser.jsp"/>
            </div>
            <div class="col-md-5">
                <div class="input-group">
                    <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown"
                            id="queryBtn"
                            aria-expanded="false" data-id="0">选择查询条件
                    </button>
                    <ul class="dropdown-menu" id="querySelect">
                        <li class="dropdown-item active" value="0" disabled>选择查询条件</li>
                        <li class="dropdown-item" value="1">按用户ID查询</li>
                        <li class="dropdown-item" value="2">按用户名查询</li>
                    </ul>
                    <input id="queryInput" type="text" class="form-control" aria-label="Text input with dropdown button"
                           disabled>
                </div>
            </div>
            <div class="col-md-2">
                <div class="dropdown" style="text-align: center;">
                    <button class="btn btn-outline-primary dropdown-toggle" type="button" id="roleDropdown"
                            data-bs-toggle="dropdown" aria-expanded="false">
                        选择角色
                    </button>
                    <ul class="dropdown-menu" aria-labelledby="roleDropdown" id="role-select">
                        <!-- 动态加载角色选项 -->
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <div class="table-responsive">
        <table class="table mx-auto text-center">
            <thead>
            <tr>
                <th scope="col">用户id</th>
                <th scope="col">用户名</th>
                <th scope="col">角色</th>
                <th scope="col">操作</th>
                <th scope="col">状态</th>
            </tr>
            </thead>
            <tbody>
            <c:forEach items="${page.items}" var="user">
                <tr
                <c:choose>
                    <c:when test="${roleId == 1}">
                        <c:if test="${user.id == 1 || user.id == 4}">
                            'disabled'
                        </c:if>
                    </c:when>
                    <c:when test="${roleId == 2 || roleId == 3}">
                        ''
                    </c:when>
                    <c:when test="${roleId == 4}">
                        <c:if test="${user.id == 1 || user.id == 4}">
                            'disabled'
                        </c:if>
                    </c:when>
                </c:choose>>
                <td id="userId">${user.id}</td>
                <td>${user.name}</td>
                <td>
                    <c:choose>
                        <c:when test="${roleId == 3}">
                            <span class="role-text">
                                <c:choose>
                                    <c:when test="${user.roleId == 1}">老师</c:when>
                                    <c:when test="${user.roleId == 2}">教务</c:when>
                                    <c:when test="${user.roleId == 3}">管理员</c:when>
                                    <c:otherwise>学生</c:otherwise>
                                </c:choose>
                            </span>
                            <select class="role-select form-select" data-user-id="${user.id}" style="display: none;">
                                <option value="1" ${user.roleId == 1 ? 'selected' : ''}>老师</option>
                                <option value="2" ${user.roleId == 2 ? 'selected' : ''}>教务</option>
                                <option value="3" ${user.roleId == 3 ? 'selected' : ''}>管理员</option>
                                <option value="4" ${user.roleId == 4 ? 'selected' : ''}>学生</option>
                            </select>
                            <button class="btn btn-sm btn-outline-primary edit-role-btn">
                                <i class="bi bi-pencil me-1"></i>编辑
                            </button>
                            <button class="btn btn-sm btn-success save-role-btn" style="display: none;">
                                <i class="bi bi-save me-1"></i>保存
                            </button>
                            <button class="btn btn-sm btn-secondary cancel-role-btn" style="display: none;">
                                <i class="bi bi-x-circle me-1"></i>取消
                            </button>
                        </c:when>
                        <c:otherwise>
                            <c:choose>
                                <c:when test="${user.roleId == 1}">
                                    老师
                                </c:when>
                                <c:when test="${user.roleId == 2}">
                                    教务
                                </c:when>
                                <c:when test="${user.roleId == 3}">
                                    管理员
                                </c:when>
                                <c:otherwise>
                                    学生
                                </c:otherwise>
                            </c:choose>
                        </c:otherwise>
                    </c:choose>
                </td>
                <td>
                    <!-- Button trigger modal -->
                    <button type="button" class="btn btn-sm btn-outline-primary edit-btn" id="show-info"
                            data-bs-toggle="modal"
                            data-bs-target="#staticBackdrop" data-user-id="${user.id}"
                            data-role-id="${user.roleId}" ${user.roleId == 2 || user.roleId == 3 ? 'style="visibility: hidden;"' : ''}>
                        <i class="bi bi-info-circle me-1"></i>详情
                    </button>
                    <button class="btn btn-sm btn-outline-danger delete-btn" id="delete-info">
                        <i class="bi bi-trash me-1"></i> 删除
                    </button>
                    <!-- Modal -->
                    <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false"
                         tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
                        <div class="modal-dialog modal-dialog-scrollable">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h1 class="modal-title fs-5" id="staticBackdropLabel">用户详情</h1>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal"
                                            aria-label="Close"></button>
                                </div>
                                <div class="modal-body flex-wrap" style="padding-left: 60px; padding-right: 60px;">
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close
                                    </button>
                                    <button type="button" class="btn btn-primary">Understood</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </td>
                <td>
                    <div class="form-check form-switch" style="width: 50%;">
                        <input class="form-check-input start-info" type="checkbox" role="switch"
                            ${ user.state == true ? 'checked' : '' }>
                        <label class="form-check-label " for="start-info">启用</label>
                    </div>
                </td>
                </tr>
            </c:forEach>
            </tbody>
        </table>
    </div>
    <jsp:include page="pagination.jsp"/>
    <script>
        window.addEventListener('load', () => {
            const baseUrl = '${pageContext.request.contextPath}';
            // 页面加载时获取所有角色并动态渲染
            loadRolesAndRender();
            // 查询条件按钮
            const $queryBtn = $('#queryBtn');
            const $queryBtnLi = $('#querySelect li');
            const $queryInput = $('#queryInput');
            // // 找到id查询按钮
            // const userIdBtn = document.getElementById('userIdBtn');
            // // 找到用户名查询按钮
            // const userNameBtn = document.getElementById('userNameBtn');
            // 找到详情按钮
            const showInfoBtns = document.querySelectorAll("#show-info");
            // 找到删除按钮
            const deleteInfoBtns = document.querySelectorAll("#delete-info");
            // 找到模态框
            const modal = document.querySelector("#staticBackdrop");
            // 找到模态框的body
            const modalBody = modal.querySelector(".modal-body");
            // 找到每个用户的启用禁用按钮
            const $startInfoBtns = $(".start-info");
            // 找到编辑按钮

            // 加载所有角色并动态渲染
            function loadRolesAndRender() {
                $.get("${pageContext.request.contextPath}/usermanage/getAllRoles", null, null, "json")
                    .done(function (result) {
                        if (result.code === 200) {
                            const roleSelect = document.getElementById('role-select');
                            if (roleSelect) {
                                roleSelect.innerHTML = '';

                                // 添加默认选项
                                const defaultLi = document.createElement('li');
                                defaultLi.innerHTML = '<a class="dropdown-item disabled" href="#">请选择角色</a>';
                                roleSelect.appendChild(defaultLi);
                                // 动态生成角色选项
                                result.data.forEach(role => {
                                    const li = document.createElement('li');
                                    li.innerHTML = '<a class="dropdown-item" href="' +
                                        baseUrl +
                                        '/usermanage/findByRoleId?roleSelect=' +
                                        role.id +
                                        '&pageIndex=1">' +
                                        role.roleName +
                                        '</a>';
                                    roleSelect.appendChild(li);
                                });
                            }
                        } else {
                            console.error('获取角色列表失败，错误码:', result.code, '消息:', result.message);
                        }
                    })
                    .fail(error => {
                        console.log(error)
                    });
            }


            // 查询按钮事件定义
            const queryByUserId = function () {
                const userId = $queryInput.val();
                const roleId = '${role.id}';
                if (userId) {
                    window.location.href =
                        '${pageContext.request.contextPath}/usermanage/findById?id=' + userId + '&roleId=' + roleId;
                }
            }

            const queryByUserName = function () {
                const username = $queryInput.val();
                const roleId = '${roleId}'; // 从JSP获取roleId
                if (username) {
                    window.location.href =
                        '${pageContext.request.contextPath}/usermanage/findByUsername?username=' + encodeURIComponent(username) + '&roleId=' + roleId;
                }
            }

            $queryBtnLi.each((index, item) => {
                item.addEventListener('click', () => {
                    $queryBtnLi.each((index1, item1) => {
                        if (index1 === index) {
                            $(item1).prop("disabled", false);
                            $(item).addClass('active');
                        } else {
                            $(item1).prop("disabled", true);
                            $(item1).removeClass('active');
                        }
                    })
                    if (index !== 0) {
                        $queryInput.prop("disabled", false);
                    } else {
                        $queryInput.prop("disabled", true);
                    }
                    // 更改按钮dataset的id属性
                    $queryBtn.data('id', index);
                    $queryBtn.text(item.innerText);
                });
            });

            // 查询输入框事件
            $queryInput.change(() => {
                console.log($queryBtn.data("id"));
                // 获取 dataset 值的正确方法
                const queryType = $queryBtn.data('id');
                // 按ID查询
                if (queryType === 1) {
                    console.log("进入1方法")
                    queryByUserId();
                }
                // 按用户名查询
                if (queryType === 2) {
                    console.log("进入2方法")
                    queryByUserName();
                }
            });

            // 详情按钮添加点击事件
            showInfoBtns.forEach(btn => {
                btn.addEventListener("click", function () {
                    $.ajax({
                        type: "GET",
                        url: "${pageContext.request.contextPath}/usermanage/showInfo",
                        data: {
                            userId: this.dataset.userId,
                            roleId: this.dataset.roleId
                        },
                        dataType: "json"
                    }).then(result => {
                        if (result.code === 200) {
                            modalBody.innerHTML = "";
                            for (let item in result.data) {
                                console.log(item);
                                const oDiv = document.createElement("div");
                                oDiv.className = "mb-3 w-100";
                                oDiv.innerHTML = `
                                <label for="` + item + `" class="form-label">` + item + `</label>
                                <input type="text" class="form-control" id="` + item + `" placeholder="Example input placeholder" value="` + result.data[item] + `" disabled>
                            `;
                                modalBody.appendChild(oDiv);
                            }
                        }
                    }).catch(error => {
                        console.log(error)
                    });
                });
            });

            // 删除按钮事件
            deleteInfoBtns.forEach(deleteInfoBtn => {
                deleteInfoBtn.addEventListener("click", function () {
                    console.log($(this).parent().siblings('#userId').text());
                    $.get("${pageContext.request.contextPath}/usermanage/deleteUser", {
                        userId: $(this).parent().siblings('#userId').text()
                    }).then(result => {
                        let resultObj = JSON.parse(result);
                        if (resultObj.code === 200) {
                            alert("删除成功");
                            window.location.reload();
                        } else {
                            alert("删除失败" + "\n" + result.message);
                        }
                    }).catch(error => {
                        console.log(error);
                    });
                });
            });

            // 状态开关事件设置
            $startInfoBtns.each(function () {
                const $this = $(this);
                $this.change(() => {
                    // 获取当前用户Id
                    const tarUserId = $this.closest('tr').find('#userId').text();

                    // 查看滑块点击后状态是否为选中状态
                    if ($this.is(':checked')) {
                        startInfoBtnHandler(tarUserId, 1);
                    } else {
                        startInfoBtnHandler(tarUserId, 0);
                    }
                });
            });

            const startInfoBtnHandler = function (tarUserId, state) {
                $.post("${pageContext.request.contextPath}/usermanage/changeState", {
                    tarUserId: tarUserId,
                    state: state
                }).then(result => {
                    if (!result) {
                        alert("服务端未响应");
                        return;
                    }
                    const resultObj = JSON.parse(result);
                    resultObj.code === 200 ? console.log("操作成功" + "\n" + resultObj.message) : alert("操作失败" + "\n" + resultObj.message);
                }).catch(error => {
                    console.log(error);
                });
            };

            // 查找节点的操作
            const findRoleElements = function (row) {
                const $row = $(row);
                return {
                    $roleText: $row.find('.role-text'),
                    $roleSelect: $row.find('.role-select'),
                    $editBtn: $row.find('.edit-role-btn'),
                    $saveBtn: $row.find('.save-role-btn'),
                    $cancelBtn: $row.find('.cancel-role-btn'),
                    $userId: $row.find('#userId')
                };
            };

            // 编辑按钮事件
            $(document).on('click', '.edit-role-btn', function () {
                const $row = $(this).closest('tr');
                const elements = findRoleElements($row);

                // 隐藏文本和编辑按钮
                elements.$roleText.hide();
                elements.$editBtn.hide();

                // 显示下拉列表和保存/取消按钮
                elements.$roleSelect.show();
                elements.$saveBtn.show();
                elements.$cancelBtn.show();
            });

            // 取消按钮事件
            $(document).on('click', '.cancel-role-btn', function () {
                const $row = $(this).closest('tr');
                const elements = findRoleElements($row);

                // 隐藏下拉列表和保存/取消按钮
                elements.$roleSelect.hide();
                elements.$saveBtn.hide();
                elements.$cancelBtn.hide();

                // 显示文本和编辑按钮
                elements.$roleText.show();
                elements.$editBtn.show();

                // 重置下拉列表选项为原始值
                const originalRole = elements.$roleText.text().trim();
                let roleValue = 4; // 默认学生

                switch (originalRole) {
                    case '老师':
                        roleValue = 1;
                        break;
                    case '教务':
                        roleValue = 2;
                        break;
                    case '管理员':
                        roleValue = 3;
                        break;
                }

                elements.$roleSelect.val(roleValue);
            });

            // 保存按钮事件
            $(document).on('click', '.save-role-btn', function () {
                const $row = $(this).closest('tr');
                const elements = findRoleElements($row);
                const userId = elements.$userId.text();
                const newRoleId = elements.$roleSelect.val();

                // 发送保存请求
                $.post("${pageContext.request.contextPath}/usermanage/changeRole", {
                    tarUserId: userId,
                    tarRoleId: newRoleId
                }).then(result => {
                    if (result) {
                        const resultObj = JSON.parse(result);
                        if (resultObj.code === 200) {
                            alert("角色修改成功");
                            location.reload();
                        } else {
                            alert("角色修改失败: " + resultObj.message);
                        }
                    }
                }).catch(error => {
                    console.log(error);
                    alert("请求失败");
                });
            });

        });
    </script>
</div>
<jsp:include page="footer.jsp"/>
